import {
  PromptTemplate,
  PromptBuildContext,
  EnhancedPromptConfig,
  ChatMode,
  Memory,
  ToolUsage,
  ConversationTurn,
  EnhancedCodeContext
} from './types';

import { PromptTemplateEngine } from './prompt-template-engine';
import { ContextManager } from './context-manager';
import { MemoryRetriever } from './memory-retriever';
import { ToolHistoryAnalyzer } from './tool-history-analyzer';
import { MessageBroker } from './message-broker';

/**
 * 提示词引擎
 * 整合所有提示词生成组件的主要接口
 */
export class PromptEngine {
  private templateEngine: PromptTemplateEngine;
  private contextManager: ContextManager;
  private memoryRetriever: MemoryRetriever;
  private toolAnalyzer: ToolHistoryAnalyzer;
  private messageBroker: MessageBroker;

  constructor(config?: EnhancedPromptConfig) {
    this.templateEngine = new PromptTemplateEngine();
    this.contextManager = new ContextManager(config?.contextPriority);
    this.memoryRetriever = new MemoryRetriever(config?.memoryRetrievalConfig);
    this.toolAnalyzer = new ToolHistoryAnalyzer(config?.toolAnalysisConfig);
    this.messageBroker = new MessageBroker();

    this.initializeDefaultTemplates();
  }

  /**
   * 构建完整的提示词
   */
  async buildPrompt(
    mode: ChatMode,
    userMessage: string,
    options: {
      conversationHistory?: ConversationTurn[];
      codeContext?: EnhancedCodeContext;
      memories?: Memory[];
      toolHistory?: ToolUsage[];
      config?: EnhancedPromptConfig;
    } = {}
  ): Promise<string> {
    // 检索相关记忆
    const relevantMemories = options.memories 
      ? this.memoryRetriever.retrieveRelevantMemories({
          mode,
          userMessage,
          conversationHistory: options.conversationHistory || [],
          variables: {}
        }, userMessage)
      : [];

    // 分析工具历史
    const toolAnalysis = options.toolHistory
      ? this.toolAnalyzer.analyzeToolHistory({
          mode,
          userMessage,
          conversationHistory: options.conversationHistory || [],
          toolHistory: options.toolHistory,
          variables: {}
        })
      : null;

    // 构建上下文
    const context = this.contextManager.buildContext(mode, userMessage, {
      conversationHistory: options.conversationHistory,
      codeContext: options.codeContext,
      memories: relevantMemories,
      toolHistory: toolAnalysis?.relevantHistory,
      maxContextLength: options.config?.maxContextLength
    });

    // 添加工具分析结果到上下文
    if (toolAnalysis) {
      context.metadata = {
        ...context.metadata,
        toolAnalysis: {
          patterns: toolAnalysis.patterns,
          recommendations: toolAnalysis.recommendations,
          summary: toolAnalysis.summary
        }
      };
    }

    // 优化上下文长度
    const optimizedContext = options.config?.maxContextLength
      ? this.contextManager.optimizeContext(context, options.config.maxContextLength)
      : context;

    // 使用模板引擎构建提示词
    return this.templateEngine.buildPrompt(optimizedContext, options.config);
  }

  /**
   * 注册自定义模板
   */
  registerTemplate(template: PromptTemplate): void {
    this.templateEngine.registerTemplate(template);
  }

  /**
   * 设置默认模板
   */
  setDefaultTemplate(mode: ChatMode, templateId: string): void {
    this.templateEngine.setDefaultTemplate(mode, templateId);
  }

  /**
   * 添加记忆
   */
  addMemory(memory: Memory): void {
    this.memoryRetriever.addMemory(memory);
  }

  /**
   * 添加工具使用记录
   */
  addToolUsage(usage: ToolUsage): void {
    this.toolAnalyzer.addToolUsage(usage);
  }

  /**
   * 获取消息代理
   */
  getMessageBroker(): MessageBroker {
    return this.messageBroker;
  }

  /**
   * 获取记忆统计
   */
  getMemoryStats() {
    return this.memoryRetriever.getMemoryStats();
  }

  /**
   * 获取工具统计
   */
  getToolStats() {
    return this.toolAnalyzer.getToolStats();
  }

  /**
   * 清理资源
   */
  dispose(): void {
    this.messageBroker.dispose();
    this.memoryRetriever.clearMemories();
    this.toolAnalyzer.clearHistory();
  }

  /**
   * 初始化默认模板
   */
  private initializeDefaultTemplates(): void {
    // Chat 模式模板
    const chatTemplate: PromptTemplate = {
      id: 'default-chat',
      name: 'Default Chat Template',
      description: 'Default template for chat mode',
      mode: ChatMode.CHAT,
      systemPrompt: `You are Augment Agent, an AI coding assistant. You help users with programming tasks, code review, and technical questions.

Current context:
- Mode: {{mode}}
- User message: {{userMessage}}`,
      sections: [
        {
          id: 'code-context',
          name: 'Code Context',
          type: 'code_context' as any,
          template: `## Current Code Context
{{#if codeContext.currentFile}}
Current file: {{codeContext.currentFile.path}}
{{#if codeContext.currentFile.content}}
\`\`\`{{codeContext.currentFile.language}}
{{codeContext.currentFile.content}}
\`\`\`
{{/if}}
{{/if}}

{{#if codeContext.selectedCode}}
Selected code:
\`\`\`
{{codeContext.selectedCode}}
\`\`\`
{{/if}}`,
          enabled: true,
          priority: 90,
          conditions: [
            {
              type: 'context',
              field: 'codeContext',
              operator: 'exists'
            }
          ]
        },
        {
          id: 'conversation-history',
          name: 'Conversation History',
          type: 'conversation' as any,
          template: `## Recent Conversation
{{#each conversationHistory}}
**{{role}}**: {{content}}
{{/each}}`,
          enabled: true,
          priority: 80,
          conditions: [
            {
              type: 'context',
              field: 'conversationHistory',
              operator: 'exists'
            }
          ],
          maxLength: 2000
        },
        {
          id: 'memories',
          name: 'Relevant Memories',
          type: 'memories' as any,
          template: `## Relevant Context
{{#each memories}}
- {{content}}
{{/each}}`,
          enabled: true,
          priority: 70,
          conditions: [
            {
              type: 'context',
              field: 'memories',
              operator: 'exists'
            }
          ],
          maxLength: 1000
        },
        {
          id: 'tool-analysis',
          name: 'Tool Usage Analysis',
          type: 'tool_history' as any,
          template: `## Tool Usage Insights
{{metadata.toolAnalysis.summary}}

{{#if metadata.toolAnalysis.recommendations}}
Recommendations:
{{#each metadata.toolAnalysis.recommendations}}
- {{this}}
{{/each}}
{{/if}}`,
          enabled: true,
          priority: 60,
          conditions: [
            {
              type: 'context',
              field: 'metadata.toolAnalysis',
              operator: 'exists'
            }
          ]
        }
      ],
      variables: {
        mode: {
          name: 'mode',
          type: 'string',
          description: 'Chat mode',
          required: true
        },
        userMessage: {
          name: 'userMessage',
          type: 'string',
          description: 'User message',
          required: true
        }
      }
    };

    // Agent 模式模板
    const agentTemplate: PromptTemplate = {
      id: 'default-agent',
      name: 'Default Agent Template',
      description: 'Default template for agent mode',
      mode: ChatMode.AGENT,
      systemPrompt: `You are Augment Agent, an autonomous AI coding assistant with access to various tools. You can read files, make edits, run commands, and perform complex coding tasks.

You have access to the following capabilities:
- File operations (read, write, edit)
- Code analysis and generation
- Tool execution
- Memory management

Current context:
- Mode: {{mode}}
- User request: {{userMessage}}`,
      sections: [
        ...chatTemplate.sections,
        {
          id: 'available-tools',
          name: 'Available Tools',
          type: 'custom' as any,
          template: `## Available Tools
You have access to various tools for file operations, code analysis, and system interaction. Use them as needed to complete the user's request.`,
          enabled: true,
          priority: 95
        }
      ],
      variables: chatTemplate.variables
    };

    // 注册模板
    this.templateEngine.registerTemplate(chatTemplate);
    this.templateEngine.registerTemplate(agentTemplate);

    // 设置默认模板
    this.templateEngine.setDefaultTemplate(ChatMode.CHAT, 'default-chat');
    this.templateEngine.setDefaultTemplate(ChatMode.AGENT, 'default-agent');
  }
}
